<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>ChRt: ChibiOS RTOS library</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
  $(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectalign" style="padding-left: 0.5em;">
   <div id="projectname">ChRt
   </div>
   <div id="projectbrief">ChibiOS/RT Arduino</div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.10 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
  <div id="navrow1" class="tabs">
    <ul class="tablist">
      <li class="current"><a href="index.html"><span>Main&#160;Page</span></a></li>
      <li><a href="files.html"><span>Files</span></a></li>
      <li>
        <div id="MSearchBox" class="MSearchBoxInactive">
        <span class="left">
          <img id="MSearchSelect" src="search/mag_sel.png"
               onmouseover="return searchBox.OnSearchSelectShow()"
               onmouseout="return searchBox.OnSearchSelectHide()"
               alt=""/>
          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)" 
               onblur="searchBox.OnSearchFieldFocus(false)" 
               onkeyup="searchBox.OnSearchFieldChange(event)"/>
          </span><span class="right">
            <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
          </span>
        </div>
      </li>
    </ul>
  </div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div class="header">
  <div class="headertitle">
<div class="title">ChibiOS RTOS library </div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><center>William Greiman</center> <center>1 Aug 2017</center><h1><a class="anchor" id="Intro"></a>
Introduction</h1>
<p>Giovanni Di Sirio is the author of ChibiOS. Giovanni has over 20 years of experience in the embedded software field.</p>
<p>Giovanni has been at STMicroelectronics since 2003, currently Software Architect in the AUTOSAR (AUTomotive Open System ARchitecture) MCAL (Microcontroller Abstraction Layer) development team based in the Arzano (Naples), automotive division.</p>
<p>This package contains a version of the ChbiOS/RT RTOS for AVR Arduinos, SAMD Arduinos, Arduino Due, and Teensy 3.x.</p>
<p>The port is based on ChibiOS 17.6.0. The ChibiOS/RT kernel is version 4.0.0.</p>
<p>These systems are packaged as the Arduino library ChRt.</p>
<p>The documentation for ChibiOS/RT 4.0.0 is located here:</p>
<p><a href="http://www.chibios.org/dokuwiki/doku.php?id=chibios:documentation:start">http://www.chibios.org/dokuwiki/doku.php?id=chibios:documentation:start</a></p>
<p>The next two sections, What an RTOS is, and What an RTOS is not, are from Giovanni's ChibiOS book at the above website.</p>
<h1><a class="anchor" id="RTOSis"></a>
What an RTOS is</h1>
<p>An RTOS is an operating system whose internal processes are guaranteed to be compliant with (hard or soft) realtime requirements. The fundamental qualities of an RTOS are:</p>
<ul>
<li>Predictability. It is the quality of being predictable in the scheduling behavior.</li>
<li>Deterministic. It is the quality of being able to consistently produce the same results under the same conditions.</li>
</ul>
<p>RTOS are often confused with “fast” operating systems. While efficiency is a positive attribute of an RTOS, efficiency alone does not qualifies an OS as RTOS but it could separate a good RTOS from a not so good one.</p>
<h1><a class="anchor" id="RTOSisNot"></a>
What an RTOS is not</h1>
<p>An RTOS is not a magic wand, your system will not be “realtime” just because you are using an RTOS, what matters is your system design. The RTOS itself is just a toolbox that offers you the required tools for creating a realtime system, you can use the tools correctly or in the wrong way.</p>
<h1><a class="anchor" id="multithread"></a>
Threadsafe and reentrant functions</h1>
<p>If this is your first exposure to a RTOS you will likely feel some pain.</p>
<p>You may want to start using ChibiOS in cooperative mode. See the chCoop.ino example below. In this mode preemptive context switches are disabled for threads of the same priority.</p>
<p>The normal Arduino environment is single-threaded so code does not need to be reentrant or threadsafe. With a preemptive RTOS, the same resources may be accessed concurrently by several threads.</p>
<p>Many arduino libraries and functions are not reentrant or threadsafe.</p>
<p>To protect resource integrity, code written for multithreaded programs must be reentrant and threadsafe.</p>
<p>Reentrance and thread safety are both related to the way that functions handle resources. Reentrance and thread safety are separate concepts: a function can be either reentrant, threadsafe, both, or neither.</p>
<p>A reentrant function does not hold static data over successive calls, nor does it return a pointer to static data. A reentrant function must not call non-reentrant functions.</p>
<p>A threadsafe function protects shared resources from concurrent access by locks. Only one thread can be executing at a time.</p>
<p>The dynamic memory functions malloc and free are not threadsafe. This means that libraries like String and SD.h are not thread safe since they use malloc/free.</p>
<p>SdFat does not use malloc but is not threadsafe. Notice that I put all access to the SD in the low priority loop thread to avoid problems.</p>
<h1><a class="anchor" id="rtosprobs"></a>
Blocking, deadlocks and priority</h1>
<p>You must not use Arduino delay() in other than the lowest priority task. delay() will block all lower priority threads.</p>
<p>Two of the most common design problems for embedded developers are the deadlock and the priority inversion problem. You should start with very simple designs to avoid these subtle problems.</p>
<h1><a class="anchor" id="errorcodes"></a>
Crash error codes</h1>
<p>I have installed simple exception error handlers for three ISR vectors. If an execution fault causes one of these exception, I blink the pin 13 LED. The codes are:</p>
<p>Hard fault - blink one short flash every two seconds</p>
<p>Bus fault - blink two short flashes every two seconds</p>
<p>Usage fault - blink three short flashes every two seconds</p>
<h1><a class="anchor" id="Examples"></a>
Examples</h1>
<p>There are a number examples. Please look at and understand these examples.</p>
<p>It is difficult to allocate the correct amount of stack memory for a thread. Several of the examples use the <a class="el" href="_ch_rt_8h.html#a9ae19ba1b487fdb8ea7d1608e64a2125">chUnusedThreadStack()</a> function to check stack usage. When a thread is created, the thread workspace is filled with a 0x55 pattern. <a class="el" href="_ch_rt_8h.html#a9ae19ba1b487fdb8ea7d1608e64a2125">chUnusedThreadStack()</a> checks how much of the 0x55 pattern has not been overwritten.</p>
<p>You should start with a generous stack size and adjust it based on the unused size.</p>
<h2><a class="anchor" id="chBlink"></a>
Two Thread Blink</h2>
<p>The chBlink.ino example demonstrates thread definition, semaphores, and thread sleep.</p>
<p>Thread 1 waits on a semaphore and turns the LED off when signaled by thread 2.</p>
<p>Thread 2 turns the LED on, sleeps for a period, signals thread 1 to turn the LED off, and sleeps for another period.</p>
<h2><a class="anchor" id="blink_print"></a>
Blink Print Example</h2>
<p>The blink/print example in each library is chBlinkPrint.ino.</p>
<p>The blink/print examples has three threads. A high priority thread blinks an LED, a medium priority thread prints a counter every second, and a low priority thread increments the counter.</p>
<p>The print thread also checks Serial for input. The print thread will displays stack usage information for each thread.</p>
<p>An interesting experiment is to observe the non-atomic behavior of incrementing count in loop().</p>
<p>Comment out noInterrupts() and interrupts() like this:</p>
<div class="fragment"><div class="line"><span class="comment">//  noInterrupts();</span></div>
<div class="line">  count++;</div>
<div class="line"><span class="comment">//  interrupts();</span></div>
</div><!-- fragment --><p>You will then see occasional large counts when the print thread tries to zero count while the loop() thread is incrementing count.</p>
<h2><a class="anchor" id="context_switch"></a>
Semaphore Context Switch Time</h2>
<p>You need an oscilloscope to run this example. This example is chContextTime.ino.</p>
<p>To run this example, connect the scope to pin 13. You will see two pulses. Measure difference in time between first pulse with no context switch and the second pulse started in ledControl and ended in ledOffTask.</p>
<p>The difference is the time for the semaphore and a context switch.</p>
<h2><a class="anchor" id="coop_schedule"></a>
Cooperative Scheduling Example</h2>
<p>ChibiOS/RT uses cooperative scheduling when CH_TIME_QUANTUM is set to zero. This disables preemption for threads with equal priority and the round robin becomes cooperative. Note that higher priority threads can still preempt, the kernel is always preemptive.</p>
<p>The chCoop.ino example illustrates this feature.</p>
<p>Note that is is not necessary to protect count or maxDelay in this example since a context switch can not happen while these variables are accessed.</p>
<h2><a class="anchor" id="data_share"></a>
Data Sharing Using a Mutex</h2>
<p>The chDataSharing.ino example illustrates thread safe data sharing between two threads.</p>
<p>Thread 1 reads a sensor into temp variables. Thread 1 calls chMtxLock() to prevent Thread 2 from accessing the shared data, and copies the temp variables to the shared area, and then unlocks access to the shared area.</p>
<p>Thread 2 runs every second. Thread 2 locks the shared data, copies the shared values to temp variables, and unlocks access to the shared area.</p>
<p>Thread 2 then prints the temp values and unused stack stats. </p>
<h2><a class="anchor" id="Event"></a>
Event Flags</h2>
<p>The chEvent.ino example demonstrates use of event flags.</p>
<h2><a class="anchor" id="fifo_logger"></a>
FIFO Data Logger</h2>
<p>The fast data logger example is chFifoDataLogger.ino. This example require connection to an SD socket.</p>
<p>Two semaphores are used to implement a FIFO for data records. This uncouples the data acquisition task from the SD write task. SD card have unpredictable write latencies that can be over 100 milliseconds.</p>
<p>You need a quality SD card to avoid data overrun errors. Overruns could be avoided by allocating more memory to the buffer queue.</p>
<p>This example logs a counter as dummy data. You can replace this with data from an analog pin or your sensor.</p>
<p>Type any character to terminate the example. Memory usage information will be printed.</p>
<h2><a class="anchor" id="delay_jitter"></a>
Delay Jitter Time</h2>
<p>The chJitter.ino example delays for one tick and measures the time difference in micros between delay calls.</p>
<p>The min and max times are printed by a lower priority task.</p>
<h2><a class="anchor" id="isr_semaphore"></a>
Task Scheduling from an Interrupt Service Routine</h2>
<p>The chIsrSemaphore.ino example demonstrates how a handler task can be triggered from an ISR by using a binary semaphore.</p>
<h2><a class="anchor" id="mailbox"></a>
Mailboxes</h2>
<p>The chMailbox.ino example demonstrates use of mailboxes.</p>
<h2><a class="anchor" id="mail_pool"></a>
Mail and Memory Pool</h2>
<p>The chMailPool.ino example demonstrates use of a memory pool and mailboxes with two senders and one receiver.</p>
<h2><a class="anchor" id="mutex_print"></a>
Mutex Protecting Serial</h2>
<p>The chMutex.ino example shows how to protect a shared resource. In this case the mutex is used to share Serial between three threads. The mutex prevents print calls from the three threads from being scrambled.</p>
<h2><a class="anchor" id="round_robin"></a>
Round Robin Scheduling</h2>
<p>chRoundRobin.ino is a very simple demonstration of two tasks running in round robin mode.</p>
<h2><a class="anchor" id="counting_Semaphore"></a>
Counting Semaphore</h2>
<p>chSemaphore.ino demonstrates use of a counting semaphore by three tasks. Execution is restrict execution of at most two tasks in one region of code. </p>
</div></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by &#160;<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.10
</small></address>
</body>
</html>
